package ar.com.ford.it.fullEconomics.view.form;

import java.sql.Timestamp;
import java.util.Calendar;
import java.util.Collection;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang.StringUtils;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.util.MessageResources;
import org.apache.struts.validator.ValidatorForm;
import ar.com.ford.it.fullEconomics.persistence.dto.Teesp02Commodity;
import ar.com.ford.it.fullEconomics.util.FullEconomicsDateUtil;

public class CommodityForm extends ValidatorForm {

    private String section;
    private String code;
    private String name;
    private String codeFind;
    private String nameFind;
    private String prefix;
    private String base;
    private String suffix;
    private String fechaIn;
    private String fechaOut;
    private Collection commoditys;
    private Teesp02Commodity commoditySelected;

    /**
     * Resetea el formulario
     * 
     */
    public void resetForm() {
        this.section = "";
        this.code = null;
        this.name = null;
        this.prefix = null;
        this.base = null;
        this.suffix = null;
        this.codeFind = null;
        this.nameFind = null;
        this.commoditys = null;
        this.commoditySelected = null;
        this.fechaIn = null;
        this.fechaOut = null;
    }

    /**
     * Limpia los campos utilizados en el form para la creacion o actualizacion
     * de Commoditys
     * 
     */
    public void clearCreateUpdateFields() {
        this.code = null;
        this.name = null;
        this.fechaIn = null;
        this.fechaOut = null;
    }

    /**
     * Setea el Commodity seleccionado para luego ser modificado
     * 
     * @param key
     * @param value
     */
    public void setEditMapped(String key, String value) {
        List commoditys = (List) this.getCommoditys();

        this.setCommoditySelected((Teesp02Commodity) commoditys.get(Integer
                .parseInt(key) - 1));
    }

    /**
     * Setea el Commodity seleccionada para luego ser eliminado
     * 
     * @param key
     * @param value
     */
    public void setDeleteMapped(String key, String value) {
        setEditMapped(key, value);
    }
    
    /**
     * Setea el Commodity seleccionada para ver sus miembros
     * 
     * @param key
     * @param value
     */
    public void setMemberMapped(String key, String value) {
        setEditMapped(key, value);
    }

    /**
     * Setea los campos del cuadro de creacion/modificacion de Commoditys
     * 
     * @param commodity
     */
    public void setCommodityForEdit(Teesp02Commodity commodity) {

        Calendar calFechaIn = Calendar.getInstance();
        calFechaIn.setTime(commodity.getEesp02CommodityInDateY());
        Calendar calFechaOut = Calendar.getInstance();
        calFechaOut.setTime(commodity.getEesp02CommodityOutDateY());

        this.setCode(String.valueOf(commodity.getEesp02CommodityNumberK()));
        this.setName(commodity.getEesp02CommodityNameN());
        this.setFechaIn(FullEconomicsDateUtil.format(calFechaIn));
        this.setFechaOut(FullEconomicsDateUtil.format(calFechaOut));
    }

    /**
     * Setea los campos del Commodity para su posterior creacion
     * 
     * @return Commodity con los campos minimos seteados para la posterior
     * creacion
     */
    public Teesp02Commodity getCommodityForCreate() {
        Teesp02Commodity commodity = new Teesp02Commodity();
        Calendar fechaCalendarIn = FullEconomicsDateUtil.format(this
                .getFechaIn());
        Timestamp tsFechaIn = new Timestamp(fechaCalendarIn.getTimeInMillis());
        Calendar fechaCalendarOut = FullEconomicsDateUtil.format(this
                .getFechaOut());
        Timestamp tsFechaOut = new Timestamp(fechaCalendarOut.getTimeInMillis());

        commodity.setEesp02CommodityNameN(this.getName());
        commodity.setEesp02CommodityInDateY(tsFechaIn);
        commodity.setEesp02CommodityOutDateY(tsFechaOut);
        return commodity;
    }

    /**
     * Setea los campos del Commodity para su posterior actualizacion
     * 
     * @param commodity
     * Commodity a actualizar
     * @return Commodity con los campos a actualizar modificados
     */
    public Teesp02Commodity getCommodityForUpdate(Teesp02Commodity commodity) {

        Calendar fechaCalendarIn = FullEconomicsDateUtil.format(this
                .getFechaIn());
        Timestamp tsFechaIn = new Timestamp(fechaCalendarIn.getTimeInMillis());
        Calendar fechaCalendarOut = FullEconomicsDateUtil.format(this
                .getFechaOut());
        Timestamp tsFechaOut = new Timestamp(fechaCalendarOut.getTimeInMillis());
        Integer code = new Integer(this.getCode());

        commodity.setEesp02CommodityNumberK(code);
        commodity.setEesp02CommodityNameN(this.getName());
        commodity.setEesp02CommodityInDateY(tsFechaIn);
        commodity.setEesp02CommodityOutDateY(tsFechaOut);

        return commodity;
    }

    /**
     * Genera las validaciones necesarias.
     */
    public ActionErrors validate(ActionMapping mapping,
                                 HttpServletRequest request) {

        ActionErrors ae = new ActionErrors();
        MessageResources resources = (MessageResources) request
                .getAttribute(org.apache.struts.Globals.MESSAGES_KEY);

        if ("find".equalsIgnoreCase(this.getSection())) {
            if (!StringUtils.isBlank(this.getCodeFind())
                    && !this.getCodeFind().matches("[0-9]+")) {
                ae.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(
                        "commodity.error.invalidCode"));
            }
        }
        if ("createUpdate".equalsIgnoreCase(this.getSection())) {

            // Verifico el codigo que no este vacio
            if (StringUtils.isBlank(this.getName())) {
                ae.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(
                        "errors.required", resources
                                .getMessage("commodity.label.name")));
            }

            try {

                // Verifico y formateo la fechas In
                if (StringUtils.isBlank(this.getFechaIn())) {
                    ae
                            .add(
                                    ActionMessages.GLOBAL_MESSAGE,
                                    new ActionMessage(
                                            "errors.required",
                                            resources
                                                    .getMessage("commodity.label.tableHeader.fechaIn")));
                } else {
                    if (FullEconomicsDateUtil.format(this.getFechaIn()) == null) {
                        ae
                                .add(
                                        ActionMessages.GLOBAL_MESSAGE,
                                        new ActionMessage(
                                                "errors.date",
                                                resources
                                                        .getMessage("commodity.label.tableHeader.fechaIn")));
                    }
                }
            } catch (Exception e) {
                ae
                        .add(
                                ActionMessages.GLOBAL_MESSAGE,
                                new ActionMessage(
                                        "errors.date",
                                        resources
                                                .getMessage("commodity.label.tableHeader.fechaIn")));
            }

            try {
                // Verifico y formateo la fechas Out
                if (StringUtils.isBlank(this.getFechaOut())) {
                    ae
                            .add(
                                    ActionMessages.GLOBAL_MESSAGE,
                                    new ActionMessage(
                                            "errors.required",
                                            resources
                                                    .getMessage("commodity.label.tableHeader.fechaOut")));

                } else {
                    if (FullEconomicsDateUtil.format(this.getFechaOut()) == null) {
                        ae
                                .add(
                                        ActionMessages.GLOBAL_MESSAGE,
                                        new ActionMessage(
                                                "errors.date",
                                                resources
                                                        .getMessage("commodity.label.tableHeader.fechaOut")));
                    }
                }
            } catch (Exception e) {
                ae
                        .add(
                                ActionMessages.GLOBAL_MESSAGE,
                                new ActionMessage(
                                        "errors.date",
                                        resources
                                                .getMessage("commodity.label.tableHeader.fechaOut")));
            }

            // Si no hubo errores
            if (ae.size() == 0)
                // Verifico que la fecha de inicio sea menor a la fecha de fin
                if (FullEconomicsDateUtil.getDifference(this.getFechaIn(), this
                        .getFechaOut()) <= 0) {
                    ae
                            .add(
                                    ActionMessages.GLOBAL_MESSAGE,
                                    new ActionMessage(
                                            "errors.date.range",
                                            resources
                                                    .getMessage("commodity.label.tableHeader.fechaOut"),
                                            resources
                                                    .getMessage("commodity.label.tableHeader.fechaIn")));
                }
        }

        return ae;
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getCodeFind() {
        return codeFind;
    }

    public void setCodeFind(String codeFind) {
        this.codeFind = codeFind;
    }

    public Collection getCommoditys() {
        return commoditys;
    }

    public void setCommoditys(Collection commoditys) {
        this.commoditys = commoditys;
    }

    public Teesp02Commodity getCommoditySelected() {
        return commoditySelected;
    }

    public void setCommoditySelected(Teesp02Commodity commoditySelected) {
        this.commoditySelected = commoditySelected;
    }

    public String getFechaIn() {
        return fechaIn;
    }

    public void setFechaIn(String fechaIn) {
        this.fechaIn = fechaIn;
    }

    public String getFechaOut() {
        return fechaOut;
    }

    public void setFechaOut(String fechaOut) {
        this.fechaOut = fechaOut;
    }

    public String getSection() {
        return section;
    }

    public void setSection(String section) {
        this.section = section;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name.toUpperCase();
    }

    public String getNameFind() {
        return nameFind;
    }

    public void setNameFind(String nameFind) {
        this.nameFind = nameFind.toUpperCase();
    }

    public String getBase() {
        return base;
    }

    public void setBase(String base) {
        this.base = base.toUpperCase();
    }

    public String getPrefix() {
        return prefix;
    }

    public void setPrefix(String prefix) {
        this.prefix = prefix.toUpperCase();
    }

    public String getSuffix() {
        return suffix;
    }

    public void setSuffix(String sufix) {
        this.suffix = sufix.toUpperCase();
    }

}
